package com.quanyan.stadium.web.api;

import com.quanyan.api.APIResponse;
import com.quanyan.common.utils.ObjectUtil;
import com.quanyan.stadium.constants.GameConstants;
import com.quanyan.stadium.entity.vo.PKEvent;
import com.quanyan.stadium.entity.vo.PKEventVo;
import com.quanyan.stadium.entity.vo.PKResultVo;
import com.quanyan.stadium.enums.PkEventStatusEnum;
import com.quanyan.stadium.service.PKEventService;
import com.quanyan.stadium.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by lei.w on 16/6/23.
 */
@RestController
@RequestMapping("/api/stadium/pkEvent")
public class PKEventController {

    private static final Logger logger = LoggerFactory.getLogger(PKEventController.class);

    @Autowired
    PKEventService pkEventService;


    @RequestMapping(value = "/createPKEvent", method = RequestMethod.POST)
    public APIResponse<?> createPKEvent(HttpServletRequest  request,@RequestBody PKEvent pkEvent) {

        try {
            System.out.println("createPKEvent pkEvent:"+ pkEvent+"  "+System.currentTimeMillis());
            logger.info("createPKEvent pkEventVo:"+ pkEvent);

            // 参数校验
            if (ObjectUtil.isObjectEmpty(pkEvent.getGameSystem(),pkEvent.getToId(), pkEvent.getType(), pkEvent.getCategoryId(), pkEvent.getPayType(), pkEvent.getBeginTime1())
                    || StringUtils.isEmpty(pkEvent.getAddress())) {
                logger.info("createPKEvent param is null.");
                return APIResponse.returnFail("param error.");
            }

            // 类型值校验
            if (pkEvent.getType() > 1) {
                logger.info("createPKEvent param type is val.");
                return APIResponse.returnFail("Parameter type value is not legitimate");
            }

            // 支付类型值校验
            if (pkEvent.getPayType() > 2) {
                logger.info("createPKEvent param payType is val.");
                return APIResponse.returnFail("Parameter payType value is not legitimate");
            }

            if (pkEvent.getBeginTime1().longValue() <= System.currentTimeMillis()) {
                logger.info("createPKEvent param beginTime1 is val.");
                return APIResponse.returnFail("Parameter beginTime1 value is not legitimate");
            }

            if (ObjectUtil.isNotObjectEmpty(pkEvent.getBeginTime2()) && pkEvent.getBeginTime2().longValue() <= System.currentTimeMillis()) {
                logger.info("createPKEvent param beginTime2 is val.");
                return APIResponse.returnFail("Parameter beginTime2 value is not legitimate");
            }

            if (ObjectUtil.isNotObjectEmpty(pkEvent.getBeginTime3()) && pkEvent.getBeginTime3().longValue() <= System.currentTimeMillis()) {
                logger.info("createPKEvent param beginTime3 is val.");
                return APIResponse.returnFail("Parameter beginTime3 value is not legitimate");
            }


            // 设置用户信息
            if (pkEvent.getType().byteValue() == GameConstants.TEAM_TYPE_CLUB) {
                pkEvent.setUid((Integer) request.getAttribute("uid"));
            } else {
                pkEvent.setFromId((Integer) request.getAttribute("uid"));
            }

            // 设置PK初始化状态
            pkEvent.setStatus(0);

            return APIResponse.returnSuccess(pkEventService.createPKEvent(pkEvent));
        } catch (Exception e) {
            logger.error("createPKEvent is error. e:", e);

            return APIResponse.returnFail(e.getMessage());
        }
    }

    @RequestMapping(value = "/queryUserCreatePKList", method = RequestMethod.POST)
    public APIResponse<?> queryUserCreatePKList(HttpServletRequest  request,@RequestBody PKEvent pkEvent) {
        try {

            if (ObjectUtil.isObjectEmpty(pkEvent.getType())) {
                return APIResponse.returnFail("param is null");
            }

            // 设置用户id
            Integer id = (Integer) request.getAttribute("uid");
            if (pkEvent.getType().byteValue() == GameConstants.TEAM_TYPE_CLUB) {
                id = pkEvent.getFormId();
            }

            logger.info("queryUserCreatePKList PKEventVo:"+ pkEvent.toString());

            return APIResponse.returnSuccess(pkEventService.queryUserCreatePKList(id, PkEventStatusEnum.PK_STATUS_CONFIRM.getId(),pkEvent.getType()));
        } catch (Exception e) {
            logger.error("queryUserCreatePKList is failed. ", e);
            return APIResponse.returnFail("Server exception");
        }

    }

    @RequestMapping(value = "/queryUserReceivePKList", method = RequestMethod.POST)
    public APIResponse<?> queryUserReceivePKList(HttpServletRequest request, @RequestBody PKEvent pkEvent) {
        try {
            // 设置用户id
            logger.info("queryUserReceivePKList PKEventVo:"+ pkEvent.toString());
            if (ObjectUtil.isObjectEmpty(pkEvent.getType())) {
                logger.info("queryUserReceivePKList type is null");
                return APIResponse.returnFail("param is null");
            }

            Integer id = (Integer) request.getAttribute("uid");
            if (pkEvent.getType().byteValue() == GameConstants.TEAM_TYPE_CLUB) {
                id = pkEvent.getToId();
            }

            return APIResponse.returnSuccess(pkEventService.queryUserReceivePKList(id, PkEventStatusEnum.PK_STATUS_CONFIRM.getId(), pkEvent.getType()));
        } catch (Exception e) {
            logger.error("queryUserReceivePKList is failed. e", e);
            return APIResponse.returnFail("Server exception");
        }
    }

    @RequestMapping(value = "/getPKInfoById", method = RequestMethod.POST)
    public APIResponse<?> getPKInfoById(HttpServletRequest request, @RequestBody PKEventVo pkEventVo) {
        try {

            Integer uid = (Integer)request.getAttribute("uid");
            if (pkEventVo.getId() == null) {
                logger.info("getUserCreatePKById param is null.");
                return APIResponse.returnFail("param error.");
            }

            pkEventVo = pkEventService.getPKInfoByIdAndUid(uid, pkEventVo.getId());

            return APIResponse.returnSuccess(pkEventVo);
        } catch (Exception e) {
            return APIResponse.returnFail("Server exception");
        }
    }

    @RequestMapping(value = "/updatePKStatus", method = RequestMethod.POST)
    public APIResponse<?> updatePKStatus(HttpServletRequest  request,@RequestBody PKEventVo pkEventVo) {
        try {
            logger.info("updatePKStatus PKEventVo:"+ pkEventVo.toString());

            if (ObjectUtil.isObjectEmpty(pkEventVo.getBeginTime(), pkEventVo.getId(), pkEventVo.getStatus())){
                return APIResponse.returnFail("param is null");
            }

            if (!pkEventService.updatePKStatus(pkEventVo)) {
                return APIResponse.returnFail("Param is null or not modify an object");
            }

            return APIResponse.returnSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("updatePKStatus is failed. e:", e);
            return APIResponse.returnFail("Server exception");
        }
    }

    @RequestMapping(value = "/entryPKResult", method = RequestMethod.POST)
    public APIResponse<?> entryPKResult(HttpServletRequest  request,@RequestBody PKResultVo pkResultVo) {
        try {
            // 设置用户登录信息
            Integer uid = (Integer) request.getAttribute("uid");
            pkResultVo.setUid(uid);

            // 参数非空校验
            if (ObjectUtil.isObjectEmpty(pkResultVo.getId(), pkResultVo.getPkResult())) {
                logger.info("entryPKResult param is null.");
                return APIResponse.returnFail("param error.");
            }

            PKEventVo pkEventVo = pkEventService.getPKInfoById(pkResultVo.getId());

            if (ObjectUtil.isObjectEmpty(pkEventVo)) {
                logger.info("entryPKResult param pkEventId value is not legitimate");
                return APIResponse.returnFail("Parameter pkEventId value is not legitimate.");
            }

            if (pkEventVo.getType().byteValue() == GameConstants.TEAM_TYPE_PERSON) {
                pkResultVo.setEntryId(uid);
            }

            // PK 状态验证
            if (pkEventVo.getStatus().intValue() != 2) {
                logger.info("PK has ended.");
                return APIResponse.returnFail("PK has ended.");
            }

            if (pkResultVo.getPkResult() > 3 || pkResultVo.getPkResult() < 1) {
                logger.info("entryPKResult result value is not legitimate");
                return APIResponse.returnFail("Parameter pkResult value is not legitimate.");
            }

            pkEventService.entryPKResult(pkResultVo, pkEventVo);

            return APIResponse.returnSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return APIResponse.returnFail("Server exception");
        }
    }

    @RequestMapping(value = "/pkResultConfirm", method = RequestMethod.POST)
    public APIResponse<?> pkResultConfirm(HttpServletRequest  request,@RequestBody PKResultVo pkResultVo) {

        try {
            logger.info("pkResultConfirm pkResultVo:"+pkResultVo.toString());
            // 设置用户登录信息
            pkResultVo.setUid((Integer) request.getAttribute("uid"));

            // 参数非空校验
            if (ObjectUtil.isObjectEmpty(pkResultVo.getId(),pkResultVo.getIsAgree())) {
                logger.info("entryPKResult param is null.");
                return APIResponse.returnFail("param error.");
            }

            PKEventVo pkEventVo = pkEventService.getPKInfoById(pkResultVo.getId());

            if (ObjectUtil.isObjectEmpty(pkEventVo)) {
                logger.info("entryPKResult param pkEventId value is not legitimate");
                return APIResponse.returnFail("Parameter pkEventId value is not legitimate.");
            }

            pkEventService.pkResultConfirm(pkResultVo, pkEventVo);
        } catch (Exception e) {
            logger.error("pkResultConfirm is failed. e:", e);
            APIResponse.returnFail("Server is busy, please try again later");
        }

        return APIResponse.returnSuccess();
    }
}